package com.ruicar.afs.cloud.basic.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.afscase.dispatch.contract.CmsInterfaceFeign;
import com.ruicar.afs.cloud.basic.common.entity.BasicBankCard;
import com.ruicar.afs.cloud.basic.common.entity.BasicContractCustRelation;
import com.ruicar.afs.cloud.basic.common.entity.BasicCustBaseInfo;
import com.ruicar.afs.cloud.basic.common.entity.BasicMainInfo;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BasicCustBaseInfoVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.CustBaseInfoVo;
import com.ruicar.afs.cloud.basic.feign.CaseForLoanBeforeInfoFeign;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractFeginParamEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/icosCcsInterface")
@AllArgsConstructor
public class IcosCcsInterfaceController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final ContractFeginConfig contractFeginConfig;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final BasicBankCardService basicBankCardService;
    private final CmsInterfaceFeign cmsInterfaceFeign;

    @ApiOperation(value = "根据合同号码查询主借人/共借人/担保人基本信息（接口聚合ccsInterface使用）")
    @PostMapping("/custBaseInfo")
    public IResponse<BasicCustBaseInfoVo> custBaseInfo(@RequestParam("contractNo") String contractNo) {
        log.info("-------------------获取客户信息接口调用参数传入值为:{}-------------------",contractNo);
        if (EmptyUtils.isEmpty(contractNo)){
            return IResponse.fail("输入参数不得为空");
        }
        /**  贷后系统中的主借人客户号 by ZC.GUO  **/
        BasicCustBaseInfoVo afterLoanInfo = new BasicCustBaseInfoVo();
        String custNo = null;
        List<String> custNoList = basicCustBaseInfoService.findCustNoByQueryNo(contractNo);
        if (EmptyUtils.isNotEmpty(custNoList)){
            custNo = custNoList.get(0);
            log.info("-------------------获取客户信息接口查询到的custNo数据为:{}-------------------",custNo);
        }
        //如果可以使用入参contractNo查询到数据，说明是申请编号，那么就只查询这个申请编号相关的数据，否则就是证件号或者手机号，需要查询其下的所有合同
        List<BasicMainInfo> mainInfos = basicMainInfoService.list(Wrappers.<BasicMainInfo>query().lambda().eq(BasicMainInfo::getApplyNo,contractNo));

        if (EmptyUtils.isNotEmpty(custNo)){
            BasicCustBaseInfo custBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda().eq(BasicCustBaseInfo::getCustNo,custNo));
            afterLoanInfo.setCustName(custBaseInfo.getCustName());
            afterLoanInfo.setPhone(custBaseInfo.getPhone());
            afterLoanInfo.setCustRole(AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
            afterLoanInfo.setCertNo(custBaseInfo.getCertNo());
            afterLoanInfo.setCertEndDate(custBaseInfo.getCertEndDate());

            /**  申请贷款笔数 by ZC.GUO  **/
            List<BasicContractCustRelation> contractCustRelationList = Lists.newArrayList();
            if(EmptyUtils.isNotEmpty(mainInfos)&&mainInfos.size()>0){
                List<String> contractNos = Lists.newArrayList();
                for(BasicMainInfo main : mainInfos){
                    contractNos.add(main.getContractNo());
                }
                contractCustRelationList = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>query().lambda()
                        .in(BasicContractCustRelation::getContractNo,contractNos)
                        .eq(BasicContractCustRelation::getCustRole,PersonRoleTypeEnum.MAIN_PERSON));
            }else{
                contractCustRelationList = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>query().lambda()
                        .eq(BasicContractCustRelation::getCustNo,custNo));
            }

            if (EmptyUtils.isNotEmpty(contractCustRelationList)){
                for (BasicContractCustRelation custRelation:contractCustRelationList){
                    CustBaseInfoVo custBaseInfoVo = new CustBaseInfoVo();
                    custBaseInfoVo.setContractNo(custRelation.getContractNo());
                    custBaseInfoVo.setCustRole(AfsEnumUtil.key(custRelation.getCustRole()));
                    if (PersonRoleTypeEnum.MAIN_PERSON.equals(custRelation.getCustRole())) {
                        custBaseInfoVo.setDefaultFlag("1");
                    } else {
                        custBaseInfoVo.setDefaultFlag("0");
                    }
                    BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda().eq(BasicMainInfo::getContractNo,custRelation.getContractNo()));
                    if (EmptyUtils.isNotEmpty(mainInfo)){
                        custBaseInfoVo.setContractStatus(AfsEnumUtil.key(mainInfo.getContractStatus()));
                    }
                    /**  贷款银行 by ZC.GUO  **/
                    BasicBankCard basicBankCard = basicBankCardService.getOne(Wrappers.<BasicBankCard>lambdaQuery()
                            .eq(BasicBankCard::getContractNo, contractNo)
                            .eq(BasicBankCard::getCertNo, custBaseInfo.getCertNo()));
                    if (EmptyUtils.isNotEmpty(basicBankCard)){
                        custBaseInfoVo.setBankCode(basicBankCard.getBankCode());
                    }
                    afterLoanInfo.getCustBaseInfoList().add(custBaseInfoVo);
                }
                afterLoanInfo.setLoanNum(String.valueOf(contractCustRelationList.size()));
            }
        }
        /**  获取贷前的数据 by ZC.GUO  **/
        BasicCustBaseInfoVo beforeLoanInfo = new BasicCustBaseInfoVo();

        Map<String, String> headers = new HashMap<>();
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_SECRET),contractFeginConfig.getCaseClientSecret());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_ID),contractFeginConfig.getCaseClientId());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        IResponse<BasicCustBaseInfoVo> iResponse = cmsInterfaceFeign.getCustomerInfo(contractNo, headers);
        log.info("-------------------查询贷前数据,返回结果状态为:{},返回的数据量:{},返回的消息:{}-------------------",iResponse.getCode(),iResponse.getData(),iResponse.getMsg());
        if (CommonConstants.SUCCESS.equals(iResponse.getCode())){
            beforeLoanInfo = iResponse.getData();
        }
        /**  贷前贷后都没有 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(afterLoanInfo) && EmptyUtils.isEmpty(beforeLoanInfo)){
            log.info("-------------------获取客户信息接口贷前,贷后都未查询到数据-------------------");
            return IResponse.fail("未查询到任何数据");
        }
        /** 需要贷前数据   贷前贷后都有，以贷后为主，贷前数据合并 by ZC.GUO  **/
        else if(EmptyUtils.isNotEmpty(afterLoanInfo.getCertNo()) && EmptyUtils.isNotEmpty(beforeLoanInfo.getCertNo())){
            afterLoanInfo.getCustBaseInfoList().addAll(beforeLoanInfo.getCustBaseInfoList());
            afterLoanInfo.setLoanNum(String.valueOf(Integer.valueOf(afterLoanInfo.getLoanNum())+Integer.valueOf(beforeLoanInfo.getLoanNum())));
            log.info("-------------------贷前,贷后数据合并总数量为:{}-------------------",afterLoanInfo.getLoanNum());
            return IResponse.success(afterLoanInfo);
        }
        /**  贷后有贷前没有 by ZC.GUO  **/
        else if(EmptyUtils.isNotEmpty(afterLoanInfo.getCertNo()) && EmptyUtils.isEmpty(beforeLoanInfo.getCertNo())){
            log.info("-------------------获取客户信息接口贷前未查询到数据,贷后获取到{}条数据-------------------",afterLoanInfo.getLoanNum());
            return IResponse.success(afterLoanInfo);
        }
        /**  贷前有贷后没有 by ZC.GUO  **/
        else{
            log.info("-------------------获取客户信息接口贷后未查询到数据,贷前获取到{}条数据-------------------",beforeLoanInfo.getLoanNum());
            return IResponse.success(beforeLoanInfo);
        }
    }
}







